﻿using AppDataStruct;
using ComLib.ComType;
using ComUIControl;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json;
using SoftKeyBoard;
using System;
using System.Windows.Forms;

namespace IPCPages
{
    public partial class PageReadPassport : PageControlBase
    {     
        private DeviceControl _device = null;
        private IDCardAll _cardInfo = null;
        private PictureBox pictureBox1 = null;
        private Label labelInputTip = null;
        private Button buttonInputID = null;
        public PageReadPassport()
        {
            InitializeComponent();
            SetProcessBase(ProcessReadPassport.Instance);
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
            buttonInputID = GetControl<Button>("buttonInputID") as Button;
            if (null != labelInputTip)
                labelInputTip.Parent = pictureBox1;
            if (null != buttonInputID)
                buttonInputID.Parent = pictureBox1;           
            countdownControl1.Parent = pictureBox1;
            SetButtonDefaultStyles(buttonCancel);
            buttonNext.Parent = pictureBox1;
            buttonCancel.Parent = pictureBox1;
            buttonBack.Parent = pictureBox1;
        }

        /// <summary>
        /// 保存身份证信息，用于预受理
        /// </summary>
        private void SetSFZData()
        {
            SFZInfo info = new SFZInfo();
            info.Address = _cardInfo.address;
            info.BirthDate = _cardInfo.birthday;
            info.ExpiryDate = _cardInfo.validtermOfStart + "-" + _cardInfo.validtermOfEnd;
            info.HeaderPicturePath = _cardInfo.HeadImage;
            info.IsManualInputNumberVerify = _cardInfo.IsManualInputNumberVerify;
            info.IssueUnit = _cardInfo.signdate;
            info.Name = _cardInfo.name;
            info.Nation = _cardInfo.people;
            info.Sex = _cardInfo.sex;
            info.SFZH = _cardInfo.number;
            Process.SetValue("SFZInfo", info);
        }

        //初始化窗体数据
        public override void InitData()
        {
            _device = new DeviceControl("PassportReader");
            _device.OnCatchException = OnCatchException;
            _device.OnWorkingDone = OnReadSuccess;
            _device.OnWorkingFailed = OnReadFailed;
            _device.OnTimeout = OnReadTimeout;
            _device.Init();
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            if(UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                SetSFZData();
            }
            Process.SetValue("IDCardInfo", _cardInfo);
            string personDir = _config.OutputDirs[_cardInfo.number];
            Process.SetValue("PersonDataDirectory", personDir);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            if (_device != null)
            {
                _device.Dispose();
                _device = null;
            }
            _cardInfo = null;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {

        }

        public override void StartWork()
        {
            Speak("请将本人护照翻开到照片页，并放置于护照阅读区");
            _device.Start();
        }

        public override void StopWork()
        {
            if(_device != null)
            {
                _device.Stop();
            }    
            base.StopWork();
        }

        private void OnReadSuccess(string outParams)
        {
            string msg = string.Format("读取结果: \n{0}", outParams);
            Log.WriteAsync(msg);

            // 在这里处理身份证信息解析结果
            _cardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);

            if (string.IsNullOrEmpty(_cardInfo.number))
            {
                MessageBox.Show("获取证件号码失败.Get Document No. Fail");
                Process.ToHome();
                return;
            }
            Action<string> handler = (e) =>
            {
                UpdateData();
                Process.ToNext();
            };
            this.Invoke(handler, msg);           
        }

        private void OnReadFailed(string outParams, string error)
        {
            string msg = string.Format("护照信息读取错误({0}): \n{1}", outParams, error);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                Process.ToHome();
            };
            this.Invoke(handler, msg);           
        }

        private void OnReadTimeout(string outParams)
        {
            string msg = string.Format("读取护照信息超时: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                Process.ToHome();
            };
            this.Invoke(handler, msg);           
        }

        private void OnCatchException(string outParams)
        {
            string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                Process.ToHome();
            };
            this.Invoke(handler, msg);            
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            StopWork();
            base.OnCountdownCompleted(sender, e);
        }

        private void buttonInputID_Click(object sender, EventArgs e)
        {
            string inputIDNumber = "";
            StopWork();
            if (StartManualInput(ref inputIDNumber))
            {
                _cardInfo = new IDCardAll();
                _cardInfo.number = inputIDNumber;
                //_cardInfo.birthday = IDCardCheck.GetBirthday(inputIDNumber);
                //_cardInfo.sex = IDCardCheck.GetSex(inputIDNumber);
                _cardInfo.IsManualInputNumberVerify = true;
                UpdateData();
                Process.ToNext();
            }
            else
            {
                StartWork();
            }
        }

        private bool StartManualInput(ref string inputStringValue)
        {
            bool bRet = false;
            Log.WriteAsync("用户启动了护照人工输入操作...");
            FormKeyInputing formInputID = new FormKeyInputing();
            Speak("请输入您的护照号码");
            if (formInputID.ShowDialog() == DialogResult.OK)
            {
                inputStringValue = formInputID.InputString;
                bRet = true;
            }
            else
            {
                Log.WriteAsync("用户取消了人工输入...");
                bRet = false;
            }
            return bRet;
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            StopWork();
            base.btnCancel_Click(sender, e);
        }        
    }
}
